package com.demo.resourcecode.c11mvc;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

/**执行过程：1、执行preHandle，返回true，继续；返回false，则直接结束；2、执行处理器逻辑，包含控制器的功能；3、执行postHandle；4、执行视图解析和视图渲染；5、执行afterCompletion
 * 配置多个拦截器，对于preHandle采用先注册先执行，而postHandle和afterCompletion则是先注册后执行；
 * 如果多个拦截器，其中一个preHandle返回false，preHandle方法会执行，但是一旦返回false，则后续的拦截器、处理器和所有postHandle方法都不会被执行。afterCompletion则不一样，他只会执行返回true的拦截器的完成方法，而且顺序是先注册后执行
 * @author zhangsulei
 *
 */
public class MyTestInterceptor implements HandlerInterceptor {

	public MyTestInterceptor(){
		System.out.println("init interceptor");
	}

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		long starttime = System.currentTimeMillis();
		request.setAttribute("starttime", starttime);
		return true;
	}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
		long starttime = (Long)request.getAttribute("starttime");
		request.removeAttribute("starttime");
		long endtime = System.currentTimeMillis();
		System.out.println(endtime - starttime);
	}

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
		System.out.println("completion");
	}

}
